/**
 * @Controller Powers（超级管理员）
 */
const Controller = require('egg').Controller;


class PowersController extends Controller {

    /**
     * @Router GET /api/v1/powers
     * @Request query number page 当前页（1）
     * @Request query number pageSize 分页大小（20）
     * @Request header string authorization
     * @Response 200 baseResponse 响应
     * @Summary 查询权限列表
     */
    async index() {
        const ctx = this.ctx;
        try {
            const powerList = await ctx.service.power.findPower(ctx.query);
            ctx.body = {
                code: 200,
                data: powerList,
                success: true,
                msg: ``
            };
        }
        catch (err) {
            throw err;
        }
    }

    /**
     * @Router POST /api/v1/powers
     * @Request body ceratePowersRequest ceratePowersRequest 创建权限
     * @Request header string authorization
     * @Response 200 baseResponse 响应
     * @Summary 创建权限
     */
    async create() {
        const ctx = this.ctx;
        ctx.validate(ctx.rule.ceratePowersRequest, ctx.request.body);
        try {
            const power = await ctx.service.power.findOnePower({
                value: ctx.request.body.value
            });
            if (power) {
                throw new Error('权限值已经存在')
            }
            const newPower = await ctx.service.power.createPower(ctx.request.body);
            ctx.body = {
                code: 200,
                data: newPower,
                success: true,
                msg: ``
            };
        }
        catch (err) {
            throw err;
        }

    };

    
    /**
     * @Router PUT /api/v1/powers:id
     * @Request header string authorization
     * @Request body ceratePowersRequest ceratePowersRequest 创建权限
     * @Response 200 baseResponse 响应
     * @Summary 更新权限
     */
    async update() {
        const ctx = this.ctx;
        ctx.validate(ctx.rule.ceratePowersRequest, ctx.request.body);
        const result = await ctx.service.power.updateOnePower({_id: ctx.params.id}, ctx.request.body);
        if(result.ok) {
            ctx.body = {
                code: 200,
                data: {},
                success: true,
                msg: `修改成功`
            }
        }
    }
}
module.exports = PowersController;